package org.example.yidaiyilu;
import org.apache.commons.io.FileUtils;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.example.yidaiyilu.entity.CiTiao;
import org.example.yidaiyilu.entity.YiXiang;
import org.example.yidaiyilu.entity.ZiTiao;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTBorder;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class YiDaiYiLuMain {

    public static void main(String[] args) throws Exception {
        String text = getText("d:\\北语项目\\“一带一路”中文解字释词词典（W）.docx");
        //String text = getText("d:\\北语项目\\一带一路测试.docx");
        splitZiTiao(text);
        toFile();
    }

    public static void toFile() throws Exception{
        StringBuilder sb = new StringBuilder();
        sb.append("<词典>");
        for(int i=0; i<ziTiaos.size(); i++){
            sb.append(ziTiaos.get(i).toString());
        }
        sb.append("</词典>");
        FileUtils.write(new File("D:\\北语项目\\“一带一路”中文解字释词词典（W）.xml"), sb.toString(), "utf-8");
    }

    public static String getText(String filePath) throws IOException {

        StringBuilder sb = new StringBuilder();
        try (FileInputStream fis = new FileInputStream(filePath)) {
            XWPFDocument document = new XWPFDocument(fis);

            // 遍历文档中的每一个段落
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                // 遍历段落中的每一个Run
                for (XWPFRun run : paragraph.getRuns()) {
                    String text = run.getText(0);
                    CTR ctr = run.getCTR();
                    System.out.println(text);
                    System.out.println(ctr.xmlText());
                    if(!run.isStrikeThrough()){
                        if (run.getFontSize() > 13) {
                            if(!"".equals(text.trim()))
                                sb.append("[字头]").append(text).append("[/字头]");
                        } else {
                            if(ctr.xmlText().indexOf("F077")!=-1) {
                                sb.append("※");
                            }else if(ctr.xmlText().indexOf("F045")!=-1){
                                sb.append("◎");
                            }
                            if (ctr.isSetRPr()) {
                                // 检查是否有边框（Border）
                                if (ctr.getRPr().isSetBdr()) {
                                    sb.append("[词性]").append(text).append("[/词性]");
                                } else{
                                    if(text!=null && !"".equals(text)){
                                        if (ctr.getRPr() != null && ctr.getRPr().getVertAlign() != null) {
                                            String vertAlign = ctr.getRPr().getVertAlign().getVal().toString();
                                            if ("superscript".equals(vertAlign)) {
                                                sb.append("[上标]").append(text).append("[/上标]");
                                            } else if ("subscript".equals(vertAlign)) {
                                                sb.append("[下标]").append(text).append("[/下标]");
                                            }
                                        } else {
                                            sb.append(text);
                                        }

                                    }
                                }
                            }
                        }
                    }
                }
                sb.append("\r\n");
            }

            document.close();
            System.out.println(sb.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            return sb.toString();
        }
    }


    private static String formatText(String srcText){
        return srcText.replaceAll("[字头]","")
                .replaceAll("","");
    }
    private static List<ZiTiao> ziTiaos = new ArrayList<ZiTiao>();



    static Pattern ciMuPat = Pattern.compile("^\\[字头\\](.*?)\\[/字头\\]\\s*(\\[上标\\]([1-9\\s]+)\\[/上标\\])*\\s*([āáǎàēéěèīíǐìōóǒòūúǔùǘǚǜa-zɡɑ'’∥\\-\\s]+)*([0-9]+画)*\\s*([^部]{1,5}部)*\\s*([左右上下中独体半包围]+)*");


    static Pattern lingjianPat = Pattern.compile("另见[^页]+页[^。]+。");
    public static void splitZiTiao(String sentence) {
        String[] sentences = sentence
                .replace("[字头]", "######[字头]")
                .split("######");
              ZiTiao zitiao = null;
        for(int i = 0; i < sentences.length; i++){
            String segment = sentences[i];
            //System.out.println(segment);
            zitiao = new ZiTiao();
            Matcher mat = ciMuPat.matcher(segment.trim());
            String zitouLine = "";
            while(mat.find()) {
                zitouLine = mat.group();
                zitiao.setZimu(mat.group(1));
                zitiao.setTongxingxuhao(mat.group(3));
                zitiao.setPinyin(mat.group(4));
                zitiao.setBihua(mat.group(5));
                zitiao.setBushou(mat.group(6));
                zitiao.setJiegou(mat.group(7));
            }
            String lingjianStr = "";
            Matcher lingjianMat = lingjianPat.matcher(segment.trim());
            if(lingjianMat.find()){
                lingjianStr = lingjianMat.group();
                zitiao.setLingjian(lingjianStr);
            }
            String zitiaoyixiangStr = segment.replace(zitouLine,"")
                    .replace(lingjianStr,"")
                    .replaceAll("([\u2776-\u277F])","★$1")
                    .replaceAll("([\u2461-\u2473])","☆$1")
                    ;
            splitZiTiaoYixiang(zitiaoyixiangStr, zitiao);

            ziTiaos.add(zitiao);
        }


    }

    static Pattern zitouyixiangPat = Pattern.compile("([\u2776-\u277F])*\\s*(\\[词性\\](.*?)\\[/词性\\])*([^◎※【$]+)*(◎[^※◎【$]+)*(※[^◎【$]+)*(◎([^—◎★☆$【]+—[^—◎★☆$【]+)(?:[◎★☆$【]))*(◎[^※◎【$]+)*");
    public static void splitZiTiaoYixiang(String zitiaoyixiangStr, ZiTiao zitiao){
        // 辨析词条,剔除注意

        String[] zitiaoyixiangList = zitiaoyixiangStr.split("★");

        for(int i = 0; i < zitiaoyixiangList.length; i++){
            if(!"".equals(zitiaoyixiangList[i].trim())) {
                String yixiangDetail = zitiaoyixiangList[i];
                Matcher mat = zitouyixiangPat.matcher(zitiaoyixiangList[i]);
                String yixiangLine = "";
                if (mat.find()) {//因为是字，只取一部分
                    List list = zitiao.getYixiangList();
                    yixiangLine = mat.group();
                    YiXiang yixiang = new YiXiang();
                    yixiang.setCixing(mat.group(3));
                    yixiang.setZh_shiyi(mat.group(4));
                    yixiang.setZhuyi(mat.group(5));
                    yixiang.setShili(mat.group(6));
                    if (mat.group(7) != null) {
                        yixiang.setBianxi(mat.group(7));
                    }
                    zitiao.setZhuyi(mat.group(9));

                    String citiaoLines = zitiaoyixiangList[i].replace(yixiangLine, "")
                            .replace("【","♥【")
                            ;
                    String[] citiaoStrs = citiaoLines.split("♥");
                    for(int j=0; j<citiaoStrs.length; j++) {
                        if (!"".equals(citiaoStrs[j].trim())) {
                            splitCiTiao(citiaoStrs[j].trim(), yixiang);
                        }
                    }
                    list.add(yixiang);
                }
            }

        }

    }

    static Pattern citiaoPat = Pattern.compile("^【([^】]+)】\\s*([āáǎàēéěèīíǐìōóǒòūúǔùǘǚǜa-zɡɑ'’∥\\-\\s]+)*");
    public static void splitCiTiao(String citiaoLine, YiXiang yiXiang){

        Matcher mat = citiaoPat.matcher(citiaoLine);
        CiTiao citiao = new CiTiao();
        String citiao_header = "";
        if(mat.find()){
            citiao_header = mat.group();
            citiao.setCimu(mat.group(1));
            citiao.setPinyin(mat.group(2));
        }
        yiXiang.getCitiaoList().add(citiao);
        String citiaoyixiangStr = citiaoLine.replace(citiao_header,"");

        splitCiTiaoYixiang(citiaoyixiangStr, citiao);
    }


    public static Pattern citiaoyixiangPat = Pattern.compile("([\u2460-\u2473])*\\s*(\\[词性\\](.*?)\\[/词性\\])*([^◎※【$]+)*(◎[^※◎【$]+)*(※[^◎【$]+)*(◎([^—◎★☆$【]+—[^—◎★☆$【]+)(?:[◎★☆$【]))*(◎[^※◎【$]+)*");
    public static void splitCiTiaoYixiang(String zitiaoyixiangStr, CiTiao citiao) {
        // 辨析词条,剔除注意

        String[] citiaoyixiangList = zitiaoyixiangStr.split("☆");


        for (int i = 0; i < citiaoyixiangList.length; i++) {
            if (!"".equals(citiaoyixiangList[i].trim())) {
                String citiaoyixiangDetail = citiaoyixiangList[i].trim();
                if(citiaoyixiangList[i].indexOf("①")!=-1){
                    System.out.println(citiaoyixiangList[i]);
                    citiao.setYixiang_header(citiaoyixiangList[i].substring(0,citiaoyixiangList[i].indexOf("①")));
                    citiaoyixiangDetail = citiaoyixiangList[i].substring(citiaoyixiangList[i].indexOf("①"));
                    System.out.println("------"+citiaoyixiangDetail);
                }
                Matcher mat = citiaoyixiangPat.matcher(citiaoyixiangDetail);
                String yixiangLine = "";
                if (mat.find()) {//因为是字，只取一部分
                    List list = citiao.getYiXiangList();
                    YiXiang yixiang = new YiXiang();
                    yixiang.setCixing(mat.group(3));
                    yixiang.setZh_shiyi(mat.group(4));
                    yixiang.setZhuyi(mat.group(5));
                    yixiang.setShili(mat.group(6));
                    if (mat.group(7) != null) {
                        yixiang.setBianxi(mat.group(7));
                    }
                    citiao.setZhuyi(mat.group(9));
                    list.add(yixiang);
                }
            }

        }
    }




}